<template>
  <div class="page-list-live">
    <PageList>
      <template #header>进出洞记录</template>
      <template #filter>
        <ListFilter :form="topFilter" @search="handleSearch" @reset="handleReset"></ListFilter>
      </template>
      <template #tips>
        <el-button icon="el-icon-delete" type="danger" @click="batchDeletion">批量删除</el-button>
      </template>
      <template #table>
        <ListTable ref="RefListTable" :loading="tableLoading" :table-data="tableData" :table-col="tableCol" @selectChange="handleSelectionChange">
          <template slot="col1" slot-scope="scope">
            <el-button icon="el-icon-document" :loading="scope.row.loadingEdit" size="mini" type="text" @click="handleRowDetails(scope.row)">详情</el-button>
            <el-button :loading="scope.row.loadingDel" size="mini" type="text" icon="el-icon-delete" style="color: red;" @click="handleRowDel(scope.row)">删除</el-button>
          </template>
        </ListTable>
      </template>
    </PageList>
    <InOutCave ref="InOutCave"></InOutCave>
  </div>
</template>
<script>
  import { parseTime } from '@/utils'
  import listMixin from '@/mixins/list'
  import InOutCave from './components/InOutCave.vue'
  import ListFilter from '@/components/ListFilter'
  import { tunnelIORecord, department, work, path } from '@/api/api'
  export default {
    components: { ListFilter, InOutCave },
    mixins: [listMixin],
    data() {
      return {
        // 定时器
        timeId: '',
        // 删除的id
        deleteList: {
          id: ''
        },
        dptList: [],
        jobList: [],
        // 查询字段
        topFilter: {
          'employee.department.id': { label: '部门', placeholder: '请选择部门', type: 'select', arr: this.dptList },
          'employee.work.id': { label: '工种', placeholder: '请选择工种', type: 'select', arr: this.workList },
          'employee.name': { label: '员工名称', placeholder: '请输入员工名称' },
          enterTime: { label: '进入隧道时间', type: 'date', arr: ['enterTime', 'leaveTime'] }
        },
        // 列表数据
        tableData: [],
        // 列表标题
        tableCol: [
          { type: 'selection' },
          {
            label: '员工名称/车辆类型', formatter(row, col, cell) {
              let deptName = ''
              if (row.carId) {
                deptName = row.car.carType
              } else if (row.employeeId) {
                deptName = row.employee.name
              }
              return deptName || '--'
            }, minWidth: '142px'
          },
          {
            label: 'RFID', formatter(row, col, cell) {
              let rfid = ''
              if (row.carId) {
                rfid = row.car.rfid
              } else if (row.employeeId) {
                rfid = row.employee.rfid
              }
              return rfid || '--'
            }
          },
          {
            label: '门禁ID/车牌号', formatter(row, col, cell) {
              let number = ''
              if (row.carId) {
                number = row.car.plateNumber
              } else if (row.employeeId) {
                number = row.employee.accessCardID
              }
              return number || '--'
            }, minWidth: '116px'
          },
          {
            label: '部门',
            formatter(row, col, cell) {
              return !row.employee ? '--' : row.employee.department ? row.employee.department.deptName : '--'
            }
          },
          {
            label: '职务',
            formatter(row, col, cell) {
              return !row.employee ? '--' : row.employee.job ? row.employee.job.jobTitle : '--'
            }
          },
          {
            label: '工种',
            formatter(row, col, cell) {
              return !row.employee ? '--' : row.employee.work ? row.employee.work.workName : '--'
            }
          },
          {
            label: '进入隧道时间',
            formatter(row, col, cell) {
              return row.enterTime ? parseTime(new Date(row.enterTime).getTime()) : '————'
            },
            minWidth: '161px'
          },
          {
            label: '离开隧道时间',
            formatter(row, col, cell) {
              return row.leaveTime ? parseTime(new Date(row.leaveTime).getTime()) : '————'
            },
            minWidth: '161px'
          },
          {
            label: '本次进洞时长',
            formatter(row, col, cell) {
              if (!row.enterTime && !row.leaveTime) { return 0 + "小时 " + 0 + "分钟" }
              if (!row.enterTime) { return 0 + "小时 " + 0 + "分钟" }
              if (!row.leaveTime) { return 0 + "小时 " + 0 + "分钟" }
              let date1 = new Date(row.enterTime)  //开始时间
              let date2 = new Date(row.leaveTime)    //结束时间
              let date3 = date2.getTime() - new Date(date1).getTime()   //时间差的毫秒数    

              //计算出相差天数
              let days = Math.floor(date3 / (24 * 3600 * 1000))

              //计算出小时数
              let leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
              let hours = Math.floor(leave1 / (3600 * 1000))

              //计算相差分钟数
              let leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
              let minutes = Math.floor(leave2 / (60 * 1000))

              return (days ? days + "天 " : '') + hours + "小时 " + minutes + "分钟"
            },
            minWidth: '161px'
          },
          { label: '操作', custom: 'col1', minWidth: '126px' }
        ]
      }
    },
    mounted() {
      this.threeList(() => {
        this.topFilter['employee.department.id'] = { label: '部门', placeholder: '请选择员工部门', type: 'select', arr: this.dptList }
        this.topFilter['employee.work.id'] = { label: '工种', placeholder: '请选择工种', type: 'select', arr: this.workList }
      })
    },
    methods: {
      // 详情
      handleRowDetails(row) {
        this.$refs['InOutCave'].open(row, '/handleRowDetails')
      },
      // 查询部门，员工
      async threeList(fn) {
        let obj = { pageIndex: 1, pageSize: 1e8 }
        let resList = await Promise.all([department('post', obj, false), work('post', obj, false)])
        // 部门
        if (resList[0].code === 200) {
          this.dptList = resList[0].data.items.map(item => {
            if (item.lenght === 0) { return }
            return {
              label: item.deptName,
              value: item.id
            }
          })
        }
        // 工种
        if (resList[1].code === 200) {
          this.workList = resList[1].data.items.map(item => {
            if (item.lenght === 0) { return }
            return {
              label: item.workName,
              value: item.id
            }
          })
        }
        fn()
      },
      // 批量删除
      batchDeletion() {
        this.$_delConfirm('选中进出洞记录', () => {
          this.delRowReq(this.deleteList)
        })
      },
      // 选中事件
      handleSelectionChange(event) {
        if (event.length > 0) {
          let ary = []
          event.forEach(item => {
            ary.push(item.id)
          })
          if (ary.length > 1) {
            this.deleteList.id = ary.join(',')
          } else {
            this.deleteList.id = ary[0]
          }
        } else {
          this.deleteList.id = ''
        }
      },
      // 请求列表数据
      async getList(query) {
        this.tableLoading = true
        try {
          let obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'createdTime', orderByAscent: false }
          const { data: { items: resData, count, pageIndex } } = await tunnelIORecord('POST', obj, false)
          this.tableData = []
          this.tableData = resData.map(item => {
            item.loadingEdit = false
            item.loadingDel = false
            return item
          })
          this.$nextTick(() => {
            this.$refs['RefListTable'].update({ page: pageIndex, count })
            this.tableLoading = false
          })
        } catch (err) {
          this.tableLoading = false
          console.error('getList err: ', err)
        }
      },
      async delRowReq(row) {
        try {
          const obj = { id: row.id, value: null }
          await tunnelIORecord('delete', obj, true)
          row.loadingDel = false
          await this.$router.push({ query: {} })
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        } catch (err) {
          row.loadingDel = false
          console.error('handleRowDel err: ', err)
        }
      },
      handleRowDel(row) {
        row.loadingDel = true
        this.$_delConfirm(
          '该进出洞记录',
          () => {
            this.delRowReq(row)
          },
          () => {
            row.loadingDel = false
          }
        )
      }
    }
  }
</script>

<style lang="scss" scoped></style>
